<script setup>
import { reactive, ref, computed, defineProps, onMounted, watch } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { nanoid } from 'nanoid'
import { ElMessage } from 'element-plus'
import { genFileId } from 'element-plus'
import { getToken } from "@/utils/auth";
import { addForm } from '@/api/complex/form'



const model = defineModel('itemList');

const currentMenu = defineModel('currentMenu')

const uploadAction = reactive({
  url: import.meta.env.VITE_APP_BASE_API + "/complex/form/upload",
  headers: { Authorization: "Bearer " + getToken() }
})

let editIndex = ref(-1);
let dialogFormVisible = ref(false)
let formLabelWidth = '140px'

let fileList = ref([])
// form 为真正意义上的临时数据
let form = reactive({
  id: null,
  itemId: null,
  itemDescription: '',
  score: '',
  ancestorName: null,
  addTimes: 1,
  file: [
    {
      name: '',
      url: ''
    }
  ]
})
//const optionData =model.value;
const search = ref('')
const upload = ref()
const selectItem = ref({})
const commitDialog = ref(false);

const dataList = ref([]);
const rules = reactive({
  addTimes: [{ required: true, message: '请输入添加次数', trigger: 'blur', type: Number }]
})

function getList() {
  const dataArray = JSON.parse(localStorage.getItem('student-form')) || [];
  if (dataArray != null && dataArray != undefined) {
    dataList.value = dataArray.filter(item => item.directoryId === currentMenu.value.directoryId);
  }
}

watchEffect(() => {

  getList()
})

const filterTableData = computed(() =>
  tableData.filter(
    (data) =>
      !search.value ||
      data.type.toLowerCase().includes(search.value.toLowerCase())
  )
)
const handleEdit = (index, row) => {
  form.itemDescription = row.itemDescription;
  form.id = row.id;
  form.ancestorName = row.ancestorName;
  form.file[0].name = row.name ? row.name : '';
  form.file[0].url = row.url ? row.url : '';
  editIndex.value = index
  const testFileData = { itemDescription: row.itemDescription, fileUrl: row.fileUrl }
  fileList.value.splice(0, 0, testFileData)
  dialogFormVisible.value = true
};
function handleDelete(data) {
  const formStore = JSON.parse(localStorage.getItem('student-form'));

  const newStore = formStore.filter((item) => {
    return item.id !== data.id;
  })
  localStorage.setItem('student-form', JSON.stringify(newStore));
  getList();
}

let tableData = reactive([]);

function addPointData() {
  const newData = {
    id: nanoid(),
    itemId: selectItem.value.itemId,
    directoryId: selectItem.value.directoryId,
    itemDescription: selectItem.value.itemDescription,
    itemScore: selectItem.value.score,
    fileName: form.file[0].name,
    fileUrl: form.file[0].url,
    addTimes: form.addTimes,
    ancestorName: form.ancestorName
  };
  // 编辑状态
  if (editIndex.value !== -1) {
    const formStorage = localStorage.getItem('student-form');
    let formStore = JSON.parse(formStorage);
    const targetIndex = formStore.findIndex((elment) => {
      return String.toString(elment.id) == String.toString(form.id);
    })
    formStore[targetIndex].itemDescription = form.itemDescription;
    formStore[targetIndex].fileUrl = newData.fileUrl;
    formStore[targetIndex].fileName = newData.fileName;
    localStorage.setItem('student-form', JSON.stringify(formStore));
    tableData.splice(editIndex.value, 1, newData);
    editIndex.value = -1;
    dialogFormVisible.value = false;
    form.itemDescription = ''
    form.file[0].name = ''
    form.itemId = null;
    form.addTimes = 1;
    fileList.value.splice(0, fileList.value.length);
    upload.value.clearFiles();
    getList()
    // 信息不全状态
  } else if (form.file[0].name === '' || form.type === '' || !form.itemId) {
    ElMessage({
      showClose: true,
      message: '请完善信息',
      type: 'error',
    })
  } else {
    let formStore = null
    let formStorage = localStorage.getItem('student-form')
    try {
      if (formStorage === null || formStorage === undefined) {
        let emptyArray = []
        emptyArray.push(newData);
        console.log(emptyArray)
        localStorage.setItem('student-form', JSON.stringify(emptyArray))
        formStore = emptyArray;
      } else {
        formStore = JSON.parse(formStorage) || [];
        formStore.push(newData);
        localStorage.setItem("student-form", JSON.stringify(formStore));
      }
      form.itemId = null;
    } catch (error) {
      localStorage.clear();
      ElMessage({
        showClose: true,
        message: '出现错误，尝试请清除缓存重试',
        type: 'error',
      })
    }
    tableData = formStore;
    console.log(fileList.value)
    dialogFormVisible.value = false;
    form.itemDescription = ''
    form.file[0].name = ''
    fileList.value.splice(0, fileList.value.length);
    upload.value.clearFiles();
    getList()
  }
  selectItem.value = {};
}
function getData(value) {

  const selectedData = model.value.find((testValue) => testValue.itemId === value)
  if (selectedData) {
    selectItem.value = selectedData;
    form.itemDescription = selectItem.value.itemDescription;
    form.score = selectItem.value.score;
    form.itemId = selectItem.value.itemId;
    form.ancestorName = selectItem.value.ancestorName;
  }
}
function handleBeforeClose(done) {
  if (editIndex.value !== -1) {
    if (fileList.value === null) {
      ElMessage({
        showClose: true,
        message: '请完善信息',
        type: 'error',
      })
    } else {
      form.itemDescription = ''
      form.file[0].name = ''
      editIndex.value = -1;
      fileList.value.splice(0, fileList.value.length);
      upload.value.clearFiles();
      done()
    }
  } else {
    form.itemDescription = ''
    form.file[0].name = ''
    done()
  }
}

function isExceedAmount() {
  if (editIndex.value !== -1) {
    ElMessage.warning('更改文件请直接重新上传即可，无需删除文件记录')
  }
  dialogFormVisible.value = true
}
function handleBeforeUpload(event) {
  form.file[0].name = event.name;
  ElMessage({
    showClose: true,
    message: '请等待文件上传成功后点击确定',
    type: 'warning',
  })
  return true;
}
const handleOnExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
  form.file[0].name = files[0].name
}
function handleOnError() {
  ElMessage({
    showClose: true,
    message: '上传文件失败，请稍后尝试',
    type: 'error',
  })
  fileList.value.splice(0, fileList.value.length);
  upload.value.clearFiles();

}
function handleOnRemove(file) {
  fileList.value.splice(0, fileList.value.length);
  upload.value.clearFiles();
  console.log(fileList.value)
}

function handleFileSuccess(res, file, fileList) {
  form.file[0].url = res.msg;
  addPointData()
}

function commit() {
  let formStorage = localStorage.getItem('student-form');
  let formStore = JSON.parse(formStorage);
  if (formStore !== null && formStore !== undefined) {
    let currentItemList = formStore.filter(item => item.itemId === selectItem.value.itemId);
    let total = form.addTimes;
    for (let index = 0; index < currentItemList.length; index++) {
      let element = currentItemList[index];
      total = total + element.addTimes;
    }
    console.log(total);
    console.log(selectItem.value.limit);
    if (total > selectItem.value.limit) {
      return ElMessage({
        showClose: true,
        message: '已经达到项目提交上限，无法提交',
        type: 'error',
      })
    }
  }
  upload.value.submit()
}



function handleCommit() {
  commitDialog.value = true;
}

function commitHandle() {
  addForm({ scoreJson: localStorage.getItem('student-form') }).then(res => {
    if (res.msg === '操作成功') {
      localStorage.clear();
      ElMessage({
        showClose: true,
        message: '提交成功',
        type: 'success'
      })
    }
  })
}

function cancelCommit() {
  commitDialog.value = false;
}

getList()
</script>

<template>
  <div class="PointsCollect">
    <div class="top-btn">
      <el-button type="primary" @click="isExceedAmount" class="btn">
        添加信息
      </el-button>
      <el-button type="primary" @click="handleCommit">
        完成填写
      </el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="handleBeforeClose" title=" 表现分数信息收集单" width="500">
      <el-form :model="form">
        <el-form-item v-model="form.type" label="分数条目类型" :label-width="formLabelWidth">
          <el-select @change="getData" v-model="form.itemId">
            <el-option v-for="t in model" :key="t.itemId" :label="t.itemDescription" :value="t.itemId" />
          </el-select>
        </el-form-item>
        <el-form-item label="添加次数" :label-width="formLabelWidth" prop="addTimes">
          <el-input v-model="form.addTimes"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="commit">
            确认
          </el-button>
        </div>
      </template>
      <el-upload v-model:file-list="fileList" class="upload-demo" drag :action="uploadAction.url" multiple
        :headers="uploadAction.headers" :before-upload="handleBeforeUpload" :on-exceed="handleOnExceed" :limit="1"
        :on-error="handleOnError" :show-file-list="true" :on-remove="handleOnRemove" :auto-upload="false" ref="upload"
        :on-success="handleFileSuccess">
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">
          拖拽文件上传或 <em>点击上传文件</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-red">
            仅限上传一个文件，超出则自动覆盖，多个文件请打成压缩包，最大不超过20MB
          </div>
        </template>
      </el-upload>
    </el-dialog>
    <el-table :data="dataList" style="width: 100%">
      <el-table-column label="条目名称" prop="itemDescription" />
      <el-table-column label="分数" prop="itemScore" />
      <el-table-column label="添加次数" prop="addTimes" />
      <el-table-column label="文件" prop="fileName" />
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="输入关键词搜索" />
        </template>
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="提交确认" v-model="commitDialog" class="confirm-dialog">
      <div style="height: 100px;font-size: 24px;">
        提交后将无法改变结果，且再被打回之前只能提交一次，是否确认提交?
      </div>
      <div class="dialog-btn">
        <el-button @click="commitHandle">确认</el-button>
        <el-button @click="cancelCommit">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.PointsCollect {
  padding-top: 18px;

  .top-btn {
    display: flex;
    justify-content: space-around;
  }
}

.btn {
  right: 0;
}

.dialog-btn {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.confirm-dialog {
  width: 200px;
  height: 400px;
}

.text-red {
  color: red;
}
</style>